package com.nju.mini_tiktok;

import android.Manifest;
import android.content.Intent;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.File;
import java.io.IOException;

public class VideoActivity extends AppCompatActivity {
    private Button opbtn;  //开启摄像头按钮
    private Button playbtn; //开始录制按钮
    private Button clobtn; //结束录制按钮
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private MediaRecorder videoRecorder;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);

        opbtn = this.findViewById(R.id.button1);
        playbtn = this.findViewById(R.id.button2);
        clobtn = this.findViewById(R.id.button3);
        videoRecorder = new MediaRecorder();
        surfaceView = this.findViewById(R.id.surfaceView1);
        surfaceHolder = surfaceView.getHolder();
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                //Log.i("camera", "surface destroyed.");
                surfaceHolder = null;
                stopRecording();
                releaseCamera();
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                //Log.i("camera", "surface destroyed");
                surfaceHolder = holder;
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                //Log.i("camera", "surface changed.");
                surfaceHolder = holder;
            }
        });
        opbtn.setOnClickListener((v) -> {
            openCamera();  //开启摄像头
        });
        playbtn.setOnClickListener((v) -> {
            benginRecording();  //开始录制
        });
        clobtn.setOnClickListener((v) -> {
            stopRecording();  //结束录制

            Intent intent = new Intent(VideoActivity.this, MainActivity.class);
            startActivity(intent);
        });
    }

    protected void stopRecording() {
        //Log.i("videoRecorder", "stopRecording...");
        if (videoRecorder != null) {
            videoRecorder.stop();
            videoRecorder.reset();
            videoRecorder.release();
            videoRecorder = null;
            camera.lock();
            releaseCamera();
        }
    }

    private void releaseCamera() {
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }

    protected void benginRecording() {
        //Log.i("videoRecorder", "beginRecording");
        //给摄像头解锁
        camera.unlock();
        //MediaRecorder获取到摄像头的访问权
        videoRecorder.setCamera(camera);
        //设置视频录制过程中所录制的音频来自手机的麦克风
        videoRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        //设置视频源为摄像头
        videoRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        //设置视频录制的输出文件为mp4文件
        videoRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        //设置音频编码方式为AAC
        videoRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        //设置录制的视频编码为H.264
        videoRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
//        videoRecorder.setVideoSize(176, 144);
//        videoRecorder.setVideoFrameRate(20);

        path = getSDPath();
        File dir = new File(path + File.separator + "AndroidVideo");
        if(!dir.exists()){
            boolean isSuccess = dir.mkdir();
            System.out.println(isSuccess);
        }
        path = dir + File.separator + System.currentTimeMillis() + ".mp4";
        videoRecorder.setOutputFile(path);
        videoRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        try {
            videoRecorder.prepare();  //将摄像头置为准备状态
            videoRecorder.start();  //开始录制
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void openCamera() {

        //Log.i("videoRecorder", "openCamera.");
        try {
            camera = Camera.open(); // attempt to get a Camera instance
            camera.setDisplayOrientation(90);
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            //Log.e("camera", "open camera error!");
            e.printStackTrace();
            return;
        }

        try {
            camera.setPreviewDisplay(surfaceHolder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("camera", "preview failed.");
            e.printStackTrace();
        }
        camera.startPreview();
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            return sdDir.toString();
        }

        return null;
    }
}

